package disjunction.core
{
	/**
	 *
	 *
	 * @author Nick Wiggill
	 */
	
	public class EntityListController extends Controller
	{
		//public var entities:EntityManager = new EntityManager();
		public var entities:Array = [];
		
		public override function set model(value:*):void
		{
			super.model = value;
			if (entities)
			{
				entities.model = value;
			}
		}
		/*
		public override function initialise(config:Object):void
		{
		}
		*/
		/** Add an entity model to the processing list. */
		protected function addEntity(entityModel:Object):void
		{
			model.toAdd.push(entityModel);
		}
		
		/** Remove an entity model from the processing list. */
		protected function removeEntity(entityModel:Object):void
		{
			model.toRemove.push(entityModel);
		}
		
		protected function updateEntityLists():void
		{
			var model:IEntityListModel = this.model as IEntityListModel;
			var	view:*;
			var entityModel:*;
			var entityView:*;
			

			//remove
			for each (entityModel in model.toRemove)
			{
				model.current.splice(model.current.lastIndexOf(entityModel, 0), 1);
				for each (view in views)
				{
					if	(view is EntityListView)
						(view as EntityListView).removeEntityView(entityModel);
				}
			}
			//??? also remove anything not in the active zone?
			
			//add
			for each (entityModel in model.toAdd)
			{
				//if entity(model) is active...
				model.current.push(entityModel);
				
				for each (view in views)
				{
					if	(view is EntityListView)
						(view as EntityListView).addEntityView(entityModel);	
				}
			}
			
			//clear both temp lists.
			model.toRemove.splice(0, model.toRemove.length);
			model.toAdd.splice(0, model.toAdd.length);
		}
		
		/** (abstract) When extending, remember to call updateEntityLists() or super()
		 * 	after your custom update code.
		 **/
		public override function update(timeDeltaMs:uint):void
		{
			updateEntityLists();
		}
	}
}